import pyautogui
import tkinter as tk
from PIL import ImageGrab


class ColorDetector:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("屏幕取色器")
        self.label = tk.Label(self.root, text="按 Ctrl+C 退出", font=('Arial', 14))
        self.label.pack(padx=20, pady=20)

        self.color_frame = tk.Frame(self.root, width=100, height=100)
        self.color_frame.pack()

    def update_color(self):
        try:
            x, y = pyautogui.position()

            # 使用PIL获取更精确的颜色（适用于多显示器）
            screenshot = ImageGrab.grab()
            pixel = screenshot.getpixel((x, y))

            # 更新显示
            hex_color = '#{:02x}{:02x}{:02x}'.format(*pixel)
            self.color_frame.config(bg=hex_color)
            self.label.config(text=f"坐标：({x}, {y})\nRGB: {pixel}\nHEX: {hex_color}")

            self.root.after(50, self.update_color)
        except Exception as e:
            print(f"发生错误: {e}")

    def run(self):
        self.root.after(0, self.update_color)
        self.root.mainloop()


if __name__ == "__main__":
    detector = ColorDetector()
    try:
        detector.run()
    except KeyboardInterrupt:
        print("程序已安全退出")